package com.uzai.console.service.wechatwork.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.rocketmq.wxgroup.KickGroupMemberDto;
import com.uzai.console.dto.rocketmq.wxgroup.WorkWxAddGroupMemberToFriends;
import com.uzai.console.dto.rocketmq.wxgroup.WorkWxSetGroupManager;
import com.uzai.console.dto.rocketmq.wxgroup.WorkWxSetGroupMemberToBlackList;
import com.uzai.console.dto.wechatwork.wxq.wxgroup.AddManagerDto;
import com.uzai.console.dto.wechatwork.wxq.wxgroup.DelManagerDto;
import com.uzai.console.dto.wechatwork.wxq.wxgroup.WxWorkGroupIdDto;
import com.uzai.console.dto.wechatwork.wxq.wxgroup.WxWorkGroupQuery;
import com.uzai.console.dto.wechatwork.wxq.wxgroupmenber.*;
import com.uzai.console.dto.wechatwork.wxworkcontacts.WxworkContactsQuery;
import com.uzai.console.entity.DeviceWxworkInfo;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.entity.es.*;
import com.uzai.console.mapper.DeviceWxworkInfoMapper;
import com.uzai.console.mapper.MerBaseConfigMapper;
import com.uzai.console.mapper.WxqManagePlanMapper;
import com.uzai.console.mapper.WxqWorkGroupManagePlanMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.feign.WxContactsFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.wechatwork.WxWorkGroupMemberService;
import com.uzai.console.service.wechatwork.WxWorkGroupService;
import com.uzai.console.vo.wechatprivate.wxq.wxgroupblacklist.baseconfig.WxqBlacklistBaseConfigVo;
import com.uzai.console.vo.wechatwork.wxq.wxgroup.WxWorkGroupInfoVo;
import com.uzai.console.vo.wechatwork.wxq.wxgroupmember.WxWorkGroupMemberInfoVo;
import com.uzai.console.vo.wechatwork.wxq.wxgroupmember.WxWorkGroupMemberRelationVo;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业微信-微信群成员成员
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class WxWorkGroupMemberServiceImpl implements WxWorkGroupMemberService {

    Logger logger = LoggerFactory.getLogger(WxWorkGroupMemberServiceImpl.class);

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private WxContactsFeignService wxContactsFeignService;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxqWorkGroupManagePlanMapper wxqWorkGroupManagePlanMapper;
    @Autowired
    private WxqManagePlanMapper wxqManagePlanMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private WxWorkGroupService wxWorkGroupService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;

    /**
     * 查询微信群成员列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupMemberQuery
     * @return null
     */
    public Page<WxWorkGroupMemberInfoVo> findWxWorkGroupMemberList(WxWorkGroupMemberQuery wxWorkGroupMemberQuery, Boolean tuominFlag){

        if(StringUtils.isBlank(wxWorkGroupMemberQuery.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupMemberQuery.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupMemberQuery.getGroupId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        //查询通讯录
        String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxWorkGroupMemberQuery.getMerId());

        //新建返回到页面的LIST对象
        List<WxWorkGroupMemberInfoVo> wxWorkGroupMemberInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxWorkGroupMemberInfoVo> page = new Page<>();
        wxWorkGroupMemberQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or_keyword = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(wxWorkGroupMemberQuery.getMerId())));

        //微信群
        boolQuery.must(QueryBuilders.termQuery("groupWxid", esWorkWxGroupInfo.getGroupId()));

        //微信群成员昵称
        if(StringUtils.isNotBlank(wxWorkGroupMemberQuery.getNick())){
            boolQuery.must(QueryBuilders.matchQuery("nick",wxWorkGroupMemberQuery.getNick()));
        }

        //微信群成员wxid
        if(StringUtils.isNotBlank(wxWorkGroupMemberQuery.getWxid())){
            boolQuery.must(QueryBuilders.termQuery("wxid",wxWorkGroupMemberQuery.getWxid()));
        }

        //成员状态
        if(wxWorkGroupMemberQuery.getStatus() != null){
            boolQuery.must(QueryBuilders.termQuery("status", wxWorkGroupMemberQuery.getStatus()));
        }

        //邀请人微信id
        if(StringUtils.isNotBlank(wxWorkGroupMemberQuery.getInviterWxid())){
            boolQuery.must(QueryBuilders.termQuery("inviterWxid", wxWorkGroupMemberQuery.getInviterWxid()));
        }

        //关键词搜索-群昵称
        if(StringUtils.isNotBlank(wxWorkGroupMemberQuery.getKeyword())){
            boolQuery_or_keyword.should(QueryBuilders.matchQuery("nick", wxWorkGroupMemberQuery.getKeyword()));
            boolQuery_or_keyword.should(QueryBuilders.termQuery("wxid", wxWorkGroupMemberQuery.getKeyword()));
        }

        searchSourceBuilder.query(boolQuery.must(boolQuery_or_keyword));

        //判断是否需要脱敏
        if(tuominFlag == null){
            tuominFlag = false;
        }
        String werified_group_member_wxid =  (String)redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_GROUP_MEMBER_WXID, wxWorkGroupMemberQuery.getMerId()));
        if(StringUtils.isNotBlank(werified_group_member_wxid)){
            tuominFlag = false;
        }

        //查询
        String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxWorkGroupMemberQuery.getMerId());
        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_workwx_group_member, searchSourceBuilder, wxWorkGroupMemberQuery.getSize(), wxWorkGroupMemberQuery.getFromIndex(), null, null, null, wxWorkGroupMemberQuery.getMerId());
        if(esResult.getTotalHits() == 0){ //查询不到数据，调用一次更新成员接口
            WxWorkGroupIdDto wxWorkGroupIdDto = new WxWorkGroupIdDto();
            wxWorkGroupIdDto.setMerId(wxWorkGroupMemberQuery.getMerId());
            wxWorkGroupIdDto.setId(wxWorkGroupMemberQuery.getGroupId());
            wxWorkGroupService.refreshGroupMember(wxWorkGroupIdDto);
        }

        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxWorkGroupMemberInfoVo wxWorkGroupMemberInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxWorkGroupMemberInfoVo.class);
                WxgroupMemberStatusEnum wxgroupMemberStatusEnum = WxgroupMemberStatusEnum.getValue(wxWorkGroupMemberInfoVo.getStatus());
                if(wxgroupMemberStatusEnum != null){
                    wxWorkGroupMemberInfoVo.setStatusName(wxgroupMemberStatusEnum.getDesc());
                }

                // 检查并设置拉黑原因
                try{
                    checkAndSetBlackReason(wxWorkGroupMemberInfoVo);
                }catch (Exception e){

                }

                //会员信息
                if(StringUtils.isNotBlank(wxWorkGroupMemberInfoVo.getWxid())){
                    User user = userService.findUserInfoByWxid(wxWorkGroupMemberQuery.getMerId(), wxWorkGroupMemberInfoVo.getWxid(), DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                    if(user != null){
                        wxWorkGroupMemberInfoVo.setUserId(user.getId());
                        wxWorkGroupMemberInfoVo.setBalance(user.getBalance());
                        wxWorkGroupMemberInfoVo.setIntegral(user.getIntegral());
                    }
                }

                //ES查询通讯录
                SearchSourceBuilder searchSourceBuilder_contacts = new SearchSourceBuilder();
                BoolQueryBuilder boolQuery_contacts = QueryBuilders.boolQuery();
                //运营商ID
                boolQuery_contacts.must(QueryBuilders.termQuery("merId", Tools.getLong(wxWorkGroupMemberQuery.getMerId())));
                //机器人微信id
                boolQuery_contacts.must(QueryBuilders.termQuery("deviceId", esWorkWxGroupInfo.getDeviceId()));
                //好友微信id
                boolQuery_contacts.must(QueryBuilders.termQuery("wxid", wxWorkGroupMemberInfoVo.getWxid()));
                searchSourceBuilder_contacts.query(boolQuery_contacts);
                WxworkContactsQuery wxworkContactsQuery = new WxworkContactsQuery();
                ESResult esResult_contacts = elasticsearchUtilGroupMsg.searchListData(uzai_workwx_contacts, searchSourceBuilder_contacts, wxworkContactsQuery.getSize(), wxworkContactsQuery.getFromIndex(), null, null, null, wxWorkGroupMemberQuery.getMerId());
                if(esResult_contacts != null && esResult_contacts.getTotalHits() > 0){
                    wxWorkGroupMemberInfoVo.setFriendFlag(1);
                }

                //查询是否是社群超级管理员
                String id_group = esWorkWxGroupInfo.getId() + "_" + wxWorkGroupMemberInfoVo.getWxid();
                String id_all = esWorkWxGroupInfo.getMerId() + "_all_all_" + wxWorkGroupMemberInfoVo.getWxid();
                Map<String,Object> map_group = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_SUPER_ADMIN, id_group, null);
                Map<String,Object> map_all = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_SUPER_ADMIN, id_all, null);
                if(map_group != null || map_all != null){ //只要有一个不等于空
                    wxWorkGroupMemberInfoVo.setSuperAdminFlag(1);
                }

                //是否脱敏处理
                //是否脱敏处理
                wxWorkGroupMemberInfoVo.setWxidNoTuomi(Tools.getStr(wxWorkGroupMemberInfoVo.getWxid()));
                if(tuominFlag){
                    wxWorkGroupMemberInfoVo.setWxid(DesensitizeUtil.around(Tools.getStr(wxWorkGroupMemberInfoVo.getWxid()),3,3));
                }

                wxWorkGroupMemberInfoVoList.add(wxWorkGroupMemberInfoVo);
            }
        }

        //返回到页面分页对象
        page.setRecords(wxWorkGroupMemberInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 获取被拉黑名单原因
     *
     * @param wxWorkGroupMemberInfoVo
     * @return
     */
    private void checkAndSetBlackReason(WxWorkGroupMemberInfoVo wxWorkGroupMemberInfoVo) {

        Integer blackFlag = 0;
        Integer type = null;
        String remark = "";
        // 查询私有
        Map<String, Object> privateBlack = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, wxWorkGroupMemberInfoVo.getId(), null);

        if (MapUtils.isNotEmpty(privateBlack)) {
            WxqBlacklistPrv wxPrivateBlack = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(privateBlack)), WxqBlacklistPrv.class);
            if (Objects.nonNull(wxPrivateBlack)) {
                type = wxPrivateBlack.getType();
                remark = wxPrivateBlack.getRemark();
                blackFlag = 1;
            }
        }
        // 如果为空,则查询全网黑名单
        else {
            Map<String,Object> publicBlack = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, wxWorkGroupMemberInfoVo.getWxid(), null);
            if (MapUtils.isEmpty(publicBlack)) {
                wxWorkGroupMemberInfoVo.setBlackout(blackFlag);
                return;
            }
            WxqWorkBlacklistPub wxPublicBlack  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(publicBlack)), WxqWorkBlacklistPub.class);
            if (Objects.nonNull(wxPublicBlack)) {
                type = wxPublicBlack.getType();
                remark = wxPublicBlack.getRemark();
                blackFlag = 1;
            }
        }

        StringBuilder blackReason = new StringBuilder("拉黑原因:");
        WxqBlacklistTypeEnum typeEnum = WxqBlacklistTypeEnum.getById(type);
        if (Objects.nonNull(typeEnum)) {
            blackReason.append(typeEnum.getDesc());
        }
        if (StringUtils.isNotBlank(remark)) {
            blackReason.append("(").append(remark).append(")");
        }
        wxWorkGroupMemberInfoVo.setBlackoutReason(blackReason.toString());
        wxWorkGroupMemberInfoVo.setBlackout(blackFlag);
    }

    /**
     * 踢出该群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupMemberKickDto
     * @return null
     */
    @Transactional
    public void kickWxWorkGroupMember(WxWorkGroupMemberKickDto wxWorkGroupMemberKickDto){

        if(StringUtils.isBlank(wxWorkGroupMemberKickDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupMemberKickDto.getMerId());

        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupMemberKickDto.getGroupId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        List<String> wxidList = wxWorkGroupMemberKickDto.getWxidList();

        if(wxidList == null || wxidList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择成员微信id");
        }

        if(wxidList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "每次批量操作必须少于40个");
        }

        //要踢掉的成员的wxid(多个wxid用;分割开 ,wxid数量显示 大于等于1,小于40)
        String arrWxids = wxidList.stream().collect(Collectors.joining(";"));

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupMemberKickDto.getMerId());
        if(deviceWxworkInfo != null){

            //发送踢群指令MQ消息
            MsgDto<KickGroupMemberDto> msgDto = new MsgDto<>();
            KickGroupMemberDto kickGroupMemberDto = new KickGroupMemberDto();
            kickGroupMemberDto.setGroupId(esWorkWxGroupInfo.getGroupId());
            kickGroupMemberDto.setArrWxids(arrWxids);
            msgDto.setContent(kickGroupMemberDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(esWorkWxGroupInfo.getDeviceUniqueId());
            msgDto.setMerId(wxWorkGroupMemberKickDto.getMerId());
            msgDto.setMsgType(MessageFuncEnum.KICK_GROUP_USER.getValue());
            noticeMsgPushProducerService.kickGroupUser(msgDto);

            //查询
            String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxWorkGroupMemberKickDto.getMerId());

            //修改群成员状态
            for (String wxid : wxidList){
                //群成员id：merId_groupWxid_wxid
                String id = wxWorkGroupMemberKickDto.getMerId() + "_" + esWorkWxGroupInfo.getGroupId() + "_" + wxid;
                int now = DateUtil.getNowTime();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("status",WxgroupMemberStatusEnum.KICKED.getValue()); //被踢
                jsonObject.put("quitTime", now);
                jsonObject.put("updateTime", now);
                //被踢原因
                if(StringUtils.isNotBlank(wxWorkGroupMemberKickDto.getQuitReason())){
                    jsonObject.put("quitReason", wxWorkGroupMemberKickDto.getQuitReason());
                }
                elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_workwx_group_member, id);
            }
        }
    }

    /**
     * 踢出该群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupMemberKickDto
     * @return null
     */
    @Transactional
    public void kickWxWorkGroupMemberByMemberIdList(WxWorkGroupMemberKickDto wxWorkGroupMemberKickDto){

        if(StringUtils.isBlank(wxWorkGroupMemberKickDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupMemberKickDto.getMerId());

        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupMemberKickDto.getGroupId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        List<String> idList = wxWorkGroupMemberKickDto.getIdList();

        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择成员微信id");
        }

        if(idList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "每次批量操作必须少于40个");
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxWorkGroupMemberKickDto.getMerId());
        List<String> wxidList = new ArrayList<>();
        for (String memberId : idList) {
            Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, memberId, null);
            EsWorkWxGroupMember esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
            if(esWorkWxGroupMember != null){
                wxidList.add(esWorkWxGroupMember.getWxid());
            }
        }

        if(wxidList == null || wxidList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到此群成员");
        }

        //要踢掉的成员的wxid(多个wxid用;分割开 ,wxid数量显示 大于等于1,小于40)
        String arrWxids = wxidList.stream().collect(Collectors.joining(";"));

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupMemberKickDto.getMerId());
        if(deviceWxworkInfo != null){

            //发送踢群指令MQ消息
            MsgDto<KickGroupMemberDto> msgDto = new MsgDto<>();
            KickGroupMemberDto kickGroupMemberDto = new KickGroupMemberDto();
            kickGroupMemberDto.setGroupId(esWorkWxGroupInfo.getGroupId());
            kickGroupMemberDto.setArrWxids(arrWxids);
            msgDto.setContent(kickGroupMemberDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(esWorkWxGroupInfo.getDeviceUniqueId());
            msgDto.setMerId(wxWorkGroupMemberKickDto.getMerId());
            msgDto.setMsgType(MessageFuncEnum.KICK_GROUP_USER.getValue());
            noticeMsgPushProducerService.kickGroupUser(msgDto);

            //修改群成员状态
            for (String wxid : wxidList){
                //群成员id：merId_groupWxid_wxid
                String id = wxWorkGroupMemberKickDto.getMerId() + "_" + esWorkWxGroupInfo.getGroupId() + "_" + wxid;
                int now = DateUtil.getNowTime();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("status",WxgroupMemberStatusEnum.KICKED.getValue()); //被踢
                jsonObject.put("quitTime", now);
                jsonObject.put("updateTime", now);
                //被踢原因
                if(StringUtils.isNotBlank(wxWorkGroupMemberKickDto.getQuitReason())){
                    jsonObject.put("quitReason", wxWorkGroupMemberKickDto.getQuitReason());
                }
                elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_workwx_group_member, id);
            }
        }
    }


    /**
     * 添加好友
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupMemberIdDto
     * @return null
     */
    public void addFriend(WxWorkGroupMemberIdDto wxWorkGroupMemberIdDto){

        if(StringUtils.isBlank(wxWorkGroupMemberIdDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupMemberIdDto.getMerId());
        //查询
        String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxWorkGroupMemberIdDto.getMerId());


        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupMemberIdDto.getGroupId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        if(StringUtils.isBlank(wxWorkGroupMemberIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询该成员信息
        Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, wxWorkGroupMemberIdDto.getId(), null);
        EsWorkWxGroupMember esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
        if(esWorkWxGroupMember == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该成员不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupMemberIdDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到群内企业微信机器人");
        }

        //调用添加好友接口
        MsgDto<WorkWxAddGroupMemberToFriends> msgDto = new MsgDto<>();
        WorkWxAddGroupMemberToFriends workWxAddGroupMemberToFriends = new WorkWxAddGroupMemberToFriends();
        workWxAddGroupMemberToFriends.setGroupId(esWorkWxGroupInfo.getGroupId());
        workWxAddGroupMemberToFriends.setWxid(esWorkWxGroupMember.getWxid());
        workWxAddGroupMemberToFriends.setCorpid(esWorkWxGroupMember.getCorpId());
        workWxAddGroupMemberToFriends.setVerify(""); //默认为空，有可能修改成前端页面输入
        msgDto.setContent(workWxAddGroupMemberToFriends);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupMemberIdDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.ADD_GROUPMEMBER_TO_FRIENDS.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxAddGroupmemberTofriends(msgDto);
        logger.info("--调用设置防骚扰规则接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 加入黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupMemberBlacklistDto
     * @return null
     */
    public void addBlacklist(WxWorkGroupMemberBlacklistDto wxWorkGroupMemberBlacklistDto){
        if(StringUtils.isBlank(wxWorkGroupMemberBlacklistDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupMemberBlacklistDto.getMerId());
        //查询
        String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxWorkGroupMemberBlacklistDto.getMerId());

        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupMemberBlacklistDto.getGroupId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        if(StringUtils.isBlank(wxWorkGroupMemberBlacklistDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询该成员信息
        Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, wxWorkGroupMemberBlacklistDto.getId(), null);
        EsWorkWxGroupMember esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
        if(esWorkWxGroupMember == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该成员不存在");
        }

        Integer now = DateUtil.getNowTime();

        //查询是否已经在黑名单当中
        //id为merId_groupWxid_wxid
        String id =wxWorkGroupMemberBlacklistDto.getId();
        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, id, null);
        WxqWorkBlacklistPrv wxqWorkBlacklistPrv_old  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqWorkBlacklistPrv.class);
        if(wxqWorkBlacklistPrv_old != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该成员已经在黑名单中");
        }
        
        //添加到全网黑名单
        if(wxWorkGroupMemberBlacklistDto.getAllBackFlag() != null && wxWorkGroupMemberBlacklistDto.getAllBackFlag().intValue() == 1){
            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, esWorkWxGroupMember.getWxid(), null);
            WxqWorkBlacklistPub wxqWorkBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqWorkBlacklistPub.class);
            if(wxqWorkBlacklistPub != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该成员已经在共享黑名单里");
            }
        }

        //添加到全网黑名单
        if(wxWorkGroupMemberBlacklistDto.getAllBackFlag() != null && wxWorkGroupMemberBlacklistDto.getAllBackFlag().intValue() == 1){
            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, esWorkWxGroupMember.getWxid(), null);
            WxqWorkBlacklistPub wxqWorkBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqWorkBlacklistPub.class);
            //全网黑名单中不存在
            if(wxqWorkBlacklistPub == null){
                wxqWorkBlacklistPub = new WxqWorkBlacklistPub();
                wxqWorkBlacklistPub.setId(esWorkWxGroupMember.getWxid());
                wxqWorkBlacklistPub.setMerId(esWorkWxGroupMember.getMerId());
                wxqWorkBlacklistPub.setGroupWxid(esWorkWxGroupMember.getGroupWxid());
                wxqWorkBlacklistPub.setWxid(esWorkWxGroupMember.getWxid());
                wxqWorkBlacklistPub.setNick(esWorkWxGroupMember.getNick());
                wxqWorkBlacklistPub.setHimg(esWorkWxGroupMember.getHimg());
                wxqWorkBlacklistPub.setType(wxWorkGroupMemberBlacklistDto.getType());
                wxqWorkBlacklistPub.setRemark(wxWorkGroupMemberBlacklistDto.getRemark());
                wxqWorkBlacklistPub.setCreateTime(now);
                wxqWorkBlacklistPub.setUpdateTime(now);
                //数据来源(0运营商共享 1官方采集-免费  2收费名单)
                wxqWorkBlacklistPub.setSource(0);
                //增加到全网黑名单
                elasticsearchUtil.addData(wxqWorkBlacklistPub, EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, esWorkWxGroupMember.getWxid());
            }
        }

        //拉群范围
        List<WxWorkGroupMemberKickDto> wxWorkGroupMemberKickDtoList = new ArrayList<>(); //封装踢群人数
        if(wxWorkGroupMemberBlacklistDto.getRange() == 0){//本群拉黑
            //拉入群黑名单
            WxqWorkBlacklistPrv wxqWorkBlacklistPrv = new WxqWorkBlacklistPrv();
            wxqWorkBlacklistPrv.setId(id);
            wxqWorkBlacklistPrv.setMerId(esWorkWxGroupMember.getMerId());
            wxqWorkBlacklistPrv.setGroupWxid(esWorkWxGroupMember.getGroupWxid());
            wxqWorkBlacklistPrv.setWxid(esWorkWxGroupMember.getWxid());
            wxqWorkBlacklistPrv.setNick(esWorkWxGroupMember.getNick());
            wxqWorkBlacklistPrv.setHimg(esWorkWxGroupMember.getHimg());
            wxqWorkBlacklistPrv.setType(wxWorkGroupMemberBlacklistDto.getType());
            wxqWorkBlacklistPrv.setRemark(wxWorkGroupMemberBlacklistDto.getRemark());
            wxqWorkBlacklistPrv.setCreateTime(now);
            wxqWorkBlacklistPrv.setUpdateTime(now);
            elasticsearchUtil.addData(wxqWorkBlacklistPrv, EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, id);

            //加入是否踢群临时列表
            WxWorkGroupMemberKickDto wxWorkGroupMemberKickDto = new WxWorkGroupMemberKickDto();
            wxWorkGroupMemberKickDto.setMerId(wxWorkGroupMemberBlacklistDto.getMerId());
            wxWorkGroupMemberKickDto.setGroupId(wxWorkGroupMemberBlacklistDto.getGroupId());
            List<String> wxidList = new ArrayList<>();
            wxidList.add(esWorkWxGroupMember.getWxid());
            wxWorkGroupMemberKickDto.setWxidList(wxidList);
            wxWorkGroupMemberKickDto.setQuitReason("加入黑名单，自动踢出该群");
            wxWorkGroupMemberKickDtoList.add(wxWorkGroupMemberKickDto);

        }else {//全部群拉黑
            //查询全部有管理方案的企业群
            //调用有群里方案的个人微信群
            WxWorkGroupQuery wxWorkGroupQuery = new WxWorkGroupQuery();
            wxWorkGroupQuery.setMerId(wxWorkGroupMemberBlacklistDto.getMerId());
            wxWorkGroupQuery.setManagePlanIdFlag(1); //过滤未配置管理方案的群
            //执行分页查询对象
            wxWorkGroupQuery.setSize(10);
            int currentPage = 1;
            wxWorkGroupQuery.setCurrent(currentPage);

            //查询总数
            Page<WxWorkGroupInfoVo> wxWorkGroupInfoVoPage = wxWorkGroupService.findWxWorkGroupList(wxWorkGroupQuery);
            while (wxWorkGroupInfoVoPage != null && wxWorkGroupInfoVoPage.getRecords() != null && wxWorkGroupInfoVoPage.getRecords().size() > 0) {
                for (WxWorkGroupInfoVo wxWorkGroupInfoVo : wxWorkGroupInfoVoPage.getRecords()) {
                    //查询该成员信息
                    //id为merId_groupWxid_wxid
                    String id_tmp = wxWorkGroupMemberBlacklistDto.getMerId() + "_" + wxWorkGroupInfoVo.getGroupId() + "_" + esWorkWxGroupMember.getWxid();
                    Map<String, Object> dataMp_member_tmp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, id_tmp, null);
                    EsWorkWxGroupMember esWorkWxGroupMember_tmp = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member_tmp)), EsWorkWxGroupMember.class);

                    //拉入群黑名单
                    WxqWorkBlacklistPrv wxqWorkBlacklistPrv = new WxqWorkBlacklistPrv();
                    wxqWorkBlacklistPrv.setId(id_tmp);
                    wxqWorkBlacklistPrv.setMerId(esWorkWxGroupMember.getMerId());
                    wxqWorkBlacklistPrv.setGroupWxid(wxWorkGroupInfoVo.getGroupId());
                    wxqWorkBlacklistPrv.setWxid(esWorkWxGroupMember.getWxid());
                    wxqWorkBlacklistPrv.setNick(esWorkWxGroupMember.getNick());
                    wxqWorkBlacklistPrv.setHimg(esWorkWxGroupMember.getHimg());
                    wxqWorkBlacklistPrv.setType(wxWorkGroupMemberBlacklistDto.getType());
                    wxqWorkBlacklistPrv.setRemark(wxWorkGroupMemberBlacklistDto.getRemark());
                    wxqWorkBlacklistPrv.setCreateTime(now);
                    wxqWorkBlacklistPrv.setUpdateTime(now);
                    elasticsearchUtil.addData(wxqWorkBlacklistPrv, EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, id_tmp);

                    //加入是否踢群临时列表
                    if (esWorkWxGroupMember_tmp != null && esWorkWxGroupMember_tmp.getStatus() == WxgroupMemberStatusEnum.NORMAL.getValue().intValue()) {
                        WxWorkGroupMemberKickDto wxWorkGroupMemberKickDto = new WxWorkGroupMemberKickDto();
                        wxWorkGroupMemberKickDto.setMerId(esWorkWxGroupMember_tmp.getMerId());
                        String groupId_tmp = esWorkWxGroupMember_tmp.getMerId() + "_" + wxWorkGroupInfoVo.getDeviceId() + "_" + wxWorkGroupInfoVo.getGroupId();
                        wxWorkGroupMemberKickDto.setGroupId(groupId_tmp);
                        List<String> wxidList = new ArrayList<>();
                        wxidList.add(esWorkWxGroupMember.getWxid());
                        wxWorkGroupMemberKickDto.setWxidList(wxidList);
                        wxWorkGroupMemberKickDto.setQuitReason("加入黑名单，自动踢出该群");
                        wxWorkGroupMemberKickDtoList.add(wxWorkGroupMemberKickDto);
                    }
                }

                //循环查询下一页
                currentPage++;
                wxWorkGroupQuery.setCurrent(currentPage);
                wxWorkGroupInfoVoPage = wxWorkGroupService.findWxWorkGroupList(wxWorkGroupQuery);
            }
        }

        //判断踢群列表
        if(wxWorkGroupMemberKickDtoList != null && wxWorkGroupMemberKickDtoList.size() > 0){
            //判断是否将此人踢群，根据社群黑名单是否勾选了加入黑名单成员，是否自动踢出群
            MerBaseConfig wxq_blacklist_config = merBaseConfigMapper.selectByMerId(wxWorkGroupMemberBlacklistDto.getMerId(), MerConfigKeyEnum.WXQ_WORK_BLACKLIST_CONFIG.getValue());
            if(wxq_blacklist_config != null && StringUtils.isNotBlank(wxq_blacklist_config.getVal())){
                WxqBlacklistBaseConfigVo wxqBlacklistBaseConfigVo =  JSONObject.parseObject(wxq_blacklist_config.getVal(), WxqBlacklistBaseConfigVo.class);
                //勾选了自动踢群选项，则执行踢群操作
                if(wxqBlacklistBaseConfigVo.getAutoKickFlag() != null && wxqBlacklistBaseConfigVo.getAutoKickFlag().intValue() == 1){
                    for(WxWorkGroupMemberKickDto wxWorkGroupMemberKickDto: wxWorkGroupMemberKickDtoList){
                        try {
                            kickWxWorkGroupMember(wxWorkGroupMemberKickDto);
                        }catch (Exception e){
                            logger.error("---加入黑名单----error={}", e.getMessage());
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询邀请关系
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupMemberIdDto
     * @return null
     */
    public WxWorkGroupMemberRelationVo findInviteRelation(WxWorkGroupMemberIdDto wxWorkGroupMemberIdDto){
        WxWorkGroupMemberRelationVo wxWorkGroupMemberRelationVo = new WxWorkGroupMemberRelationVo();

        if(StringUtils.isBlank(wxWorkGroupMemberIdDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupMemberIdDto.getMerId());
        //查询
        String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxWorkGroupMemberIdDto.getMerId());


        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupMemberIdDto.getGroupId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        if(StringUtils.isBlank(wxWorkGroupMemberIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询该成员信息
        Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, wxWorkGroupMemberIdDto.getId(), null);
        EsWorkWxGroupMember esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
        if(esWorkWxGroupMember == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该成员不存在");
        }

        BeanUtils.copyProperties(esWorkWxGroupMember, wxWorkGroupMemberRelationVo);

        WxgroupMemberStatusEnum wxgroupMemberStatusEnum = WxgroupMemberStatusEnum.getValue(wxWorkGroupMemberRelationVo.getStatus());
        if(wxgroupMemberStatusEnum != null){
            wxWorkGroupMemberRelationVo.setStatusName(wxgroupMemberStatusEnum.getDesc());
        }

        //会员信息
        if(StringUtils.isNotBlank(wxWorkGroupMemberRelationVo.getWxid())){
            User user = userService.findUserInfoByWxid(esWorkWxGroupInfo.getMerId(), wxWorkGroupMemberRelationVo.getWxid(), DeviceTypeEnum.DT_WORK_WECHAT.getKey());
            if(user != null){
                wxWorkGroupMemberRelationVo.setUserId(user.getId());
                wxWorkGroupMemberRelationVo.setBalance(user.getBalance());
                wxWorkGroupMemberRelationVo.setIntegral(user.getIntegral());
            }else{
                DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectByDeviceId(wxWorkGroupMemberRelationVo.getWxid());
                if(deviceWxworkInfo != null){
                    wxWorkGroupMemberRelationVo.setDeviceUniqueId(deviceWxworkInfo.getId());
                }
            }
        }

        //ES查询通讯录-是否是通讯录好友
        SearchSourceBuilder searchSourceBuilder_contacts = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_contacts = QueryBuilders.boolQuery();
        //运营商ID
        boolQuery_contacts.must(QueryBuilders.termQuery("merId", Tools.getLong(esWorkWxGroupInfo.getMerId())));
        //机器人微信id
        boolQuery_contacts.must(QueryBuilders.termQuery("deviceId", esWorkWxGroupInfo.getDeviceId()));
        //好友微信id
        boolQuery_contacts.must(QueryBuilders.termQuery("wxid", wxWorkGroupMemberRelationVo.getWxid()));
        searchSourceBuilder_contacts.query(boolQuery_contacts);
        WxWorkGroupQuery wxWorkGroupQuery = new WxWorkGroupQuery();
        ESResult esResult_contacts = elasticsearchUtilGroupMsg.searchListData(uzai_workwx_group_info, searchSourceBuilder_contacts, wxWorkGroupQuery.getSize(), wxWorkGroupQuery.getFromIndex(), null, null, null, esWorkWxGroupInfo.getMerId());
        if(esResult_contacts != null && esResult_contacts.getTotalHits() > 0){
            wxWorkGroupMemberRelationVo.setFriendFlag(1);
        }


        //递归查询下级
        List<WxWorkGroupMemberRelationVo> sonList = getSonList(wxWorkGroupMemberRelationVo, esWorkWxGroupInfo,20);
        wxWorkGroupMemberRelationVo.setSonList(sonList);

        //递归查询上级
        List<WxWorkGroupMemberRelationVo> parentList = new ArrayList<>();
        getParentList(parentList, wxWorkGroupMemberRelationVo, esWorkWxGroupInfo,20);
        Collections.reverse(parentList);
        wxWorkGroupMemberRelationVo.setParentList(parentList);
        return wxWorkGroupMemberRelationVo;
    }

    /**
     * 递归查询下级成员
     * @param wxWorkGroupMemberRelationVo 群成员
     * @param esWorkWxGroupInfo 群消息
     * @param esWorkWxGroupInfo optTimes 递归次数控制参数，最大支持50次，防止死循环，造成内存溢出
     * @return
     */
    private List<WxWorkGroupMemberRelationVo> getSonList(WxWorkGroupMemberRelationVo wxWorkGroupMemberRelationVo, EsWorkWxGroupInfo esWorkWxGroupInfo, int optTimes) {
        //只递归50次，防止数据溢出造成死循环
        if(optTimes <= 0){
            return  null;
        }

        //执行一次，就减少一次
        optTimes--;


        //查询
        String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, esWorkWxGroupInfo.getMerId());
        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, esWorkWxGroupInfo.getMerId());


        List<WxWorkGroupMemberRelationVo> wxWorkGroupMemberRelationVoList = new ArrayList<>();
        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", esWorkWxGroupInfo.getMerId()));
        //微信群
        boolQuery.must(QueryBuilders.termQuery("groupWxid", wxWorkGroupMemberRelationVo.getGroupWxid()));
        //邀请人微信id
        boolQuery.must(QueryBuilders.termQuery("inviterWxid", wxWorkGroupMemberRelationVo.getWxid()));
        searchSourceBuilder.query(boolQuery);
        WxWorkGroupMemberQuery wxWorkGroupMemberQuery = new WxWorkGroupMemberQuery();
        wxWorkGroupMemberQuery.setMerId(esWorkWxGroupInfo.getMerId());
        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_workwx_group_member, searchSourceBuilder, wxWorkGroupMemberQuery.getSize(), wxWorkGroupMemberQuery.getFromIndex(), null, null, null, esWorkWxGroupInfo.getMerId());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxWorkGroupMemberRelationVo wxWorkGroupMemberRelationVo_son  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxWorkGroupMemberRelationVo.class);
                if(wxWorkGroupMemberRelationVo_son != null){
                    WxgroupMemberStatusEnum wxgroupMemberStatusEnum = WxgroupMemberStatusEnum.getValue(wxWorkGroupMemberRelationVo_son.getStatus());
                    if(wxgroupMemberStatusEnum != null){
                        wxWorkGroupMemberRelationVo_son.setStatusName(wxgroupMemberStatusEnum.getDesc());
                    }

                    //会员信息
                    if(StringUtils.isNotBlank(wxWorkGroupMemberRelationVo_son.getWxid())) {
                        User user = userService.findUserInfoByWxid(esWorkWxGroupInfo.getMerId(), wxWorkGroupMemberRelationVo_son.getWxid(), DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                        if (user != null) {
                            wxWorkGroupMemberRelationVo_son.setUserId(user.getId());
                            wxWorkGroupMemberRelationVo_son.setBalance(user.getBalance());
                            wxWorkGroupMemberRelationVo_son.setIntegral(user.getIntegral());
                        }else{
                            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectByDeviceId(wxWorkGroupMemberRelationVo_son.getWxid());
                            if (deviceWxworkInfo != null) {
                                wxWorkGroupMemberRelationVo_son.setDeviceUniqueId(deviceWxworkInfo.getId());
                            }
                        }
                    }

                    //ES查询通讯录-是否
                    SearchSourceBuilder searchSourceBuilder_contacts = new SearchSourceBuilder();
                    BoolQueryBuilder boolQuery_contacts = QueryBuilders.boolQuery();
                    //运营商ID
                    boolQuery_contacts.must(QueryBuilders.termQuery("merId", Tools.getLong(esWorkWxGroupInfo.getMerId())));
                    //机器人微信id
                    boolQuery_contacts.must(QueryBuilders.termQuery("deviceId", esWorkWxGroupInfo.getDeviceId()));
                    //好友微信id
                    boolQuery_contacts.must(QueryBuilders.termQuery("wxid", wxWorkGroupMemberRelationVo_son.getWxid()));
                    searchSourceBuilder_contacts.query(boolQuery_contacts);
                    WxWorkGroupQuery wxWorkGroupQuery = new WxWorkGroupQuery();
                    ESResult esResult_contacts = elasticsearchUtilGroupMsg.searchListData(uzai_workwx_group_info, searchSourceBuilder_contacts, wxWorkGroupQuery.getSize(), wxWorkGroupQuery.getFromIndex(), null, null, null, esWorkWxGroupInfo.getMerId());
                    if(esResult_contacts != null && esResult_contacts.getTotalHits() > 0){
                        wxWorkGroupMemberRelationVo_son.setFriendFlag(1);
                    }
                    //递归查询下级
                    List<WxWorkGroupMemberRelationVo> sonList = getSonList(wxWorkGroupMemberRelationVo_son, esWorkWxGroupInfo, optTimes);
                    wxWorkGroupMemberRelationVo_son.setSonList(sonList);
                    wxWorkGroupMemberRelationVoList.add(wxWorkGroupMemberRelationVo_son);
                }
            }
        }
        return wxWorkGroupMemberRelationVoList;
    }

    /**
     * 递归查询上级成员
     * @param wxWorkGroupMemberRelationVo 成员信息
     * @param optTimes  optTimes 递归次数控制参数，最大支持50次，防止死循环，造成内存溢出
     * @return
     */
    private void getParentList(List<WxWorkGroupMemberRelationVo> wxWorkGroupMemberInfoVoList, WxWorkGroupMemberRelationVo wxWorkGroupMemberRelationVo, EsWorkWxGroupInfo esWorkWxGroupInfo, int optTimes) {

        //查询
        String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, esWorkWxGroupInfo.getMerId());
        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, esWorkWxGroupInfo.getMerId());


        //只递归50次，防止数据溢出造成死循环
        if(optTimes <= 0){
            return;
        }

        //执行一次，就减少一次
        optTimes--;

        //有上级
        if(StringUtils.isNotBlank(wxWorkGroupMemberRelationVo.getInviterWxid())){
            //查询该成员信息merId_groupWxid_wxid
            String id = esWorkWxGroupInfo.getMerId() + "_" + wxWorkGroupMemberRelationVo.getGroupWxid() + "_" + wxWorkGroupMemberRelationVo.getInviterWxid();
            Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, id, null);
            WxWorkGroupMemberRelationVo wxWorkGroupMemberRelationVo_parent  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), WxWorkGroupMemberRelationVo.class);
            if(wxWorkGroupMemberRelationVo_parent != null){
                WxgroupMemberStatusEnum wxgroupMemberStatusEnum = WxgroupMemberStatusEnum.getValue(wxWorkGroupMemberRelationVo_parent.getStatus());
                if(wxgroupMemberStatusEnum != null){
                    wxWorkGroupMemberRelationVo_parent.setStatusName(wxgroupMemberStatusEnum.getDesc());
                }

                //会员信息
                if(StringUtils.isNotBlank(wxWorkGroupMemberRelationVo_parent.getWxid())){
                    User user = userService.findUserInfoByWxid(esWorkWxGroupInfo.getMerId(), wxWorkGroupMemberRelationVo_parent.getWxid(), DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                    if(user != null){
                        wxWorkGroupMemberRelationVo_parent.setUserId(user.getId());
                        wxWorkGroupMemberRelationVo_parent.setBalance(user.getBalance());
                        wxWorkGroupMemberRelationVo_parent.setIntegral(user.getIntegral());
                    }else{
                        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectByDeviceId(wxWorkGroupMemberRelationVo_parent.getWxid());
                        if(deviceWxworkInfo != null){
                            wxWorkGroupMemberRelationVo_parent.setDeviceUniqueId(deviceWxworkInfo.getId());
                        }
                    }
                }

                //ES查询通讯录-是否
                SearchSourceBuilder searchSourceBuilder_contacts = new SearchSourceBuilder();
                BoolQueryBuilder boolQuery_contacts = QueryBuilders.boolQuery();
                //运营商ID
                boolQuery_contacts.must(QueryBuilders.termQuery("merId", Tools.getLong(esWorkWxGroupInfo.getMerId())));
                //机器人微信id
                boolQuery_contacts.must(QueryBuilders.termQuery("deviceId", esWorkWxGroupInfo.getDeviceId()));
                //好友微信id
                boolQuery_contacts.must(QueryBuilders.termQuery("wxid", wxWorkGroupMemberRelationVo_parent.getWxid()));
                searchSourceBuilder_contacts.query(boolQuery_contacts);
                WxWorkGroupQuery wxWorkGroupQuery = new WxWorkGroupQuery();
                ESResult esResult_contacts = elasticsearchUtilGroupMsg.searchListData(uzai_workwx_group_info, searchSourceBuilder_contacts, wxWorkGroupQuery.getSize(), wxWorkGroupQuery.getFromIndex(), null, null, null, esWorkWxGroupInfo.getMerId());
                if(esResult_contacts != null && esResult_contacts.getTotalHits() > 0){
                    wxWorkGroupMemberRelationVo_parent.setFriendFlag(1);
                }
                wxWorkGroupMemberInfoVoList.add(wxWorkGroupMemberRelationVo_parent);
                //递归查询
                getParentList(wxWorkGroupMemberInfoVoList, wxWorkGroupMemberRelationVo_parent, esWorkWxGroupInfo, optTimes);
            }
        }
    }

    /**
     * 加群黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupMemberGroupBlacklistDto
     * @return null
     */
    public void addGrpupBlacklist(WxWorkGroupMemberGroupBlacklistDto wxWorkGroupMemberGroupBlacklistDto){
        if(StringUtils.isBlank(wxWorkGroupMemberGroupBlacklistDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }
        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupMemberGroupBlacklistDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupMemberGroupBlacklistDto.getGroupId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }
        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupMemberGroupBlacklistDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }


        //成员id列表
        List<String> wxidList = new ArrayList<>();
        List<String> idList = wxWorkGroupMemberGroupBlacklistDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择加群黑名单成员");
        }

        for (String id : idList) {
            //查询
            String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxWorkGroupMemberGroupBlacklistDto.getMerId());
            //查询该成员信息
            Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, id, null);
            EsWorkWxGroupMember esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
            if(esWorkWxGroupMember != null){
                wxidList.add(esWorkWxGroupMember.getWxid());
            }
        }

        //调用加群黑名单接口
        MsgDto<WorkWxSetGroupMemberToBlackList> msgDto = new MsgDto<>();
        WorkWxSetGroupMemberToBlackList wxSetGroupMemberToBlackList = new WorkWxSetGroupMemberToBlackList();
        wxSetGroupMemberToBlackList.setStatus(1);
        wxSetGroupMemberToBlackList.setArrWxid(String.join(";", wxidList));
        msgDto.setContent(wxSetGroupMemberToBlackList);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupMemberGroupBlacklistDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SET_GROUPMEMBER_TO_BLACKLIST.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxSetgroupMembertoblacklist(msgDto);
        logger.info("--调用加群黑名单接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 设置群成员管理员
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupMemberSetAdminDto
     * @return null
     */
    public void setAdmin(WxWorkGroupMemberSetAdminDto wxWorkGroupMemberSetAdminDto){

        if(wxWorkGroupMemberSetAdminDto.getOptType() != 1 && wxWorkGroupMemberSetAdminDto.getOptType() != 2){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "操作类型不正确");
        }

        if(StringUtils.isBlank(wxWorkGroupMemberSetAdminDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupMemberSetAdminDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupMemberSetAdminDto.getGroupId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }
        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupMemberSetAdminDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }


        //成员id列表
        List<String> wxidList = new ArrayList<>();

        List<String> outWxidList = new ArrayList<>();
        List<String> idList = wxWorkGroupMemberSetAdminDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "成员id列表为空");
        }

        for (String id : idList) {
            //查询
            String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxWorkGroupMemberSetAdminDto.getMerId());
            //查询该成员信息
            Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, id, null);
            EsWorkWxGroupMember esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
            if (esWorkWxGroupMember != null && !StringUtils.isBlank(esWorkWxGroupMember.getWxid())) {
                if (esWorkWxGroupMember.getEmployeeTag() == 0) {
                    outWxidList.add(esWorkWxGroupMember.getWxid());
                }
                if (esWorkWxGroupMember.getEmployeeTag() == 1) {
                    wxidList.add(esWorkWxGroupMember.getWxid());
                }
            } else {
                int lastIndex = id.lastIndexOf("_");
                outWxidList.add(id.substring(lastIndex + 1));
            }
        }

        if (!wxidList.isEmpty()) {
            //调用设置群管理员接口
            MsgDto<WorkWxSetGroupManager> msgDto = new MsgDto<>();
            WorkWxSetGroupManager workWxSetGroupManager = new WorkWxSetGroupManager();
            workWxSetGroupManager.setGroupId(esWorkWxGroupInfo.getGroupId());
            workWxSetGroupManager.setArrWxids(String.join(";", wxidList));
            workWxSetGroupManager.setOptType(wxWorkGroupMemberSetAdminDto.getOptType());
            msgDto.setContent(workWxSetGroupManager);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
            msgDto.setMerId(wxWorkGroupMemberSetAdminDto.getMerId());
            msgDto.setMsgType(MessageFuncEnum.SET_GROUP_MANAGER.getValue());
            //调用微服务
            UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxSetgroupManager(msgDto);
            logger.info("--调用设置群成员管理员接口--para={},result={}", JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
            if (uzaiRespVo != null && uzaiRespVo.getCode() != 200) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
            }
        }

        if (!outWxidList.isEmpty() && wxWorkGroupMemberSetAdminDto.getOptType() == 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "仅支持内部成员设置为管理员,微信ID为" + String.join(",", outWxidList) + "设置失败");
        }
        if (!outWxidList.isEmpty() && wxWorkGroupMemberSetAdminDto.getOptType() == 2) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "仅支持内部成员移除,微信ID为" + String.join(",", outWxidList) + "移除失败");
        }

    }


    @Override
    public void addManager(AddManagerDto addManagerDto) {
        if(StringUtils.isBlank(addManagerDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }
        if(addManagerDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商ID不能为空");
        }
        if(addManagerDto.getWxidList()==null||addManagerDto.getWxidList().isEmpty()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        if(addManagerDto.getWxidList().size()>3){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最多设置3个管理员");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, addManagerDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, addManagerDto.getGroupId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

             //ES查询
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //运营商ID
            boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(addManagerDto.getMerId())));

            //微信群
            boolQuery.must(QueryBuilders.termQuery("groupWxid", esWorkWxGroupInfo.getGroupId()));

            boolQuery.must(QueryBuilders.termQuery("isAdmin", 1));

            searchSourceBuilder.query(boolQuery);
            //查询
            String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, addManagerDto.getMerId());

            long managerNum = elasticsearchUtilGroupMsg.searchTotal(uzai_workwx_group_member, searchSourceBuilder);

             //判断原来的群管数
            if(managerNum>=3){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最多设置3个群管,你已设置3个群管");
            }
            // 判读设置的群管数+原群管数
            if((addManagerDto.getWxidList().size()+managerNum)>3){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"最多设置3个群管，你已设置"+managerNum+"个群管,还可以设置"+(3-managerNum)+"个群管");
            }

        WxWorkGroupMemberSetAdminDto wxWorkGroupMemberSetAdminDto=new WxWorkGroupMemberSetAdminDto();
        wxWorkGroupMemberSetAdminDto.setMerId(addManagerDto.getMerId());
        wxWorkGroupMemberSetAdminDto.setGroupId(addManagerDto.getGroupId());
        wxWorkGroupMemberSetAdminDto.setOptType(1);
        wxWorkGroupMemberSetAdminDto.setIdList(addManagerDto.getWxidList());
        setAdmin(wxWorkGroupMemberSetAdminDto);
    }

    @Override
    public void delManager(DelManagerDto delManagerDto) {
        if(StringUtils.isBlank(delManagerDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }
        if(delManagerDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商ID不能为空");
        }
        if(delManagerDto.getWxidList()==null||delManagerDto.getWxidList().isEmpty()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, delManagerDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, delManagerDto.getGroupId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(delManagerDto.getMerId())));

        //微信群
        boolQuery.must(QueryBuilders.termQuery("groupWxid", esWorkWxGroupInfo.getGroupId()));

        boolQuery.must(QueryBuilders.termQuery("isAdmin", 1));

        searchSourceBuilder.query(boolQuery);

        //查询
        String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, delManagerDto.getMerId());
        long managerNum = elasticsearchUtilGroupMsg.searchTotal(uzai_workwx_group_member, searchSourceBuilder);

        if(managerNum==0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "当前无可移除的管理员");
        }

        WxWorkGroupMemberSetAdminDto wxWorkGroupMemberSetAdminDto=new WxWorkGroupMemberSetAdminDto();
        wxWorkGroupMemberSetAdminDto.setMerId(delManagerDto.getMerId());
        wxWorkGroupMemberSetAdminDto.setGroupId(delManagerDto.getGroupId());
        wxWorkGroupMemberSetAdminDto.setOptType(2);
        wxWorkGroupMemberSetAdminDto.setIdList(delManagerDto.getWxidList());
        setAdmin(wxWorkGroupMemberSetAdminDto);
    }
}
